const { Sequelize, DataTypes } = require("sequelize");
const Redis = require("ioredis");

// 从环境变量中读取数据库配置
const {
    MYSQL_USERNAME,
    MYSQL_PASSWORD,
    MYSQL_ADDRESS,
    REDIS_PASSWORD,
    REDIS_HOST,
    REDIS_PORT = "",
} = process.env;

const [host, port] = MYSQL_ADDRESS.split(":");

const sequelize = new Sequelize("nodejs_demo", MYSQL_USERNAME, MYSQL_PASSWORD, {
    host,
    port,
    dialect: "mysql" /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */ ,
});

// 定义数据模型
const Counter = sequelize.define("Counter", {
    count: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 1,
    },
});

// 数据库初始化方法
async function init() {
    await Counter.sync({ alter: true });
}

// 导出初始化方法和模型
module.exports = {
    init,
    Counter,
    redis: new Redis({
        port: REDIS_PORT,
        host: REDIS_HOST,
        family: 4,
        password: REDIS_PASSWORD,
        db: 0,
    }),
};